package com.example.administrator.printoutindemo;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.example.administrator.printoutindemo.base.BaseActivity;
import com.example.administrator.printoutindemo.bean.GetOutStorageReceiver;
import com.example.administrator.printoutindemo.bean.SpinnerItem;
import com.example.administrator.printoutindemo.mvp.ui.adapter.MeterSearchConditionAdapter;
import com.example.administrator.printoutindemo.mvp.ui.entity.GetMeterSearchCondition;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.MoHuArrayAdapter;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.base.BaseConstants.RESULT_CLOSE;

@Route(path = RouterHub.APP_STORESUBMITPROJECT1ACTIVITY)
public class StoreSubmitProject1Activity extends BaseActivity implements MeterSearchConditionAdapter.IMeterSearchConditionAdapter {

    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;
    AutoCompleteTextView s_sub1_project = null;
    AutoCompleteTextView s_sub1_targetProject = null;
    String check_user_name;
    int check_id;
    private String SYSException = "";
    private ProjectInfo projectInfo = null;
    private CheckUser checkUser = null;
    private GetOutStorageReceiver mGetOutStorageReceiver = null;
    private List<ProjectInfo> li_projectInfo = null;
    private List<CheckUser> li_checkUser = null;
    private List<GetOutStorageReceiver> mGetOutStorageReceivers = null;
    //    private MyAutoAarryAdapter projectAda = null;
    private MoHuArrayAdapter projectAda = null;
    private TextView s_sub1_userName = null;
    private TextView tv_shen_qing_dan_wei = null;
    private TextView s_sub1_outTime = null;
    //	private EditText s_sub1_material = null;
    private EditText mEtLingLiaoRen = null;
    private TextView s_sub1_receiverPhone = null;
    private EditText mEtLingLiaoRenDianHua = null;
    private EditText s_sub1_receiveAdd = null;
    private LinearLayout mLlDianBiaoChaXunTiaoJian;
    private Button login_btn_next = null;
    private SharedPreferences sPreferencces;
    private TextView btnRight;
    private NiceSpinner niceSpinner;
    private NiceSpinner niceSpinnerLingLiaoRen;
    private String receiveUser; //下拉选领料人
    @SuppressLint("HandlerLeak")

    private String mUserId;

    private String mLingLiaoLeiXing = "";
    private String mSearchcondition = "";
    private String mSelectedDisplayname = "";
    private String mSelectedValuename = "";
    private String mSelectedValue = "";
    private Spinner spinner_1;
    private Spinner spinner_2;
    private NestedScrollView nsv;
    private RecyclerView recyclerView;
    private ArrayAdapter<String> spinnerAdapter1;
    private ArrayAdapter<String> spinnerAdapter2;
    private List<String> mSpinnerList1 = new ArrayList<>();
    private List<String> mSpinnerList2 = new ArrayList<>();
    private MeterSearchConditionAdapter mMeterSearchConditionAdapter;
    private List<String> mMeterSearchConditionList = new ArrayList<>();
    private HashMap<String, ArrayList<String>> valuesHashMap = new HashMap<>();
    private HashMap<String, String> valuenamesHashMap = new HashMap<>();

    /**
     * 判断两个日期的大小
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean isDate2Bigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = false;
        } else if (dt1.getTime() <= dt2.getTime()) {
            isBigger = true;
        }
        return isBigger;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CLOSE) {
            setResult(RESULT_CLOSE);
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_activity_submitproject_1);
        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.ling_liao_shen_qing));
        mLlDianBiaoChaXunTiaoJian = (LinearLayout) findViewById(R.id.ll_dian_biao_cha_xun_tiao_jian);
        s_sub1_project = (AutoCompleteTextView) findViewById(R.id.s_sub1_project);// 项目
        niceSpinnerLingLiaoRen = (NiceSpinner) findViewById(R.id.ns_ling_liao_ren);// 项目
        btnRight = (TextView) findViewById(R.id.btnRight);// 项目
        spinner_1 = (Spinner) findViewById(R.id.spinner_1);
        spinner_2 = (Spinner) findViewById(R.id.spinner_2);
        nsv = (NestedScrollView) findViewById(R.id.nsv);
        s_sub1_targetProject = (AutoCompleteTextView) findViewById(R.id.s_sub1_targetProject);// 目的项目
        s_sub1_userName = (TextView) findViewById(R.id.s_sub1_userName);
        tv_shen_qing_dan_wei = (TextView) findViewById(R.id.tv_shen_qing_dan_wei);
        s_sub1_outTime = (TextView) findViewById(R.id.s_sub1_outTime);// 出库时间
//		s_sub1_material = (EditText) findViewById(R.id.s_sub1_material);// 物料描述
        mEtLingLiaoRen = (EditText) findViewById(R.id.et_ling_liao_ren);// 领料人
        s_sub1_receiverPhone = (TextView) findViewById(R.id.s_sub1_receiverPhone);// 领料人电话
        mEtLingLiaoRenDianHua = (EditText) findViewById(R.id.et_ling_liao_ren_dian_hua);//领料人电话
        s_sub1_receiveAdd = (EditText) findViewById(R.id.s_sub1_receiveAdd);// 到货地点
        login_btn_next = (Button) findViewById(R.id.login_btn_next);// 下一步按钮

        projectInfo = new ProjectInfo();
        checkUser = new CheckUser();
        mGetOutStorageReceiver = new GetOutStorageReceiver();

        View.OnClickListener s_sub1_outTime_timeListener = new BtnOnClickListener(
                1);

        s_sub1_outTime.setOnClickListener(s_sub1_outTime_timeListener);

        btnRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//                int check_id = ((SpinnerItem) s_sub1_checker.getSelectedItem()).GetID();

//                String check_user_name = ((SpinnerItem) s_sub1_checker.getSelectedItem()).GetValue();
//                String check_user_name = ((SpinnerItem) niceSpinner.getSelectedIndex()).GetValue();
                String projectName = s_sub1_project.getText().toString().trim();
                String outTime = s_sub1_outTime.getText().toString();
                String lingLiaoRen = mEtLingLiaoRen.getText().toString();
//                String receivePhone = s_sub1_receiverPhone.getText().toString();
                String lingLiaoRenDianHua = mEtLingLiaoRenDianHua.getText().toString();
                String receiveAdd = s_sub1_receiveAdd.getText().toString();
                String targetProjectName = s_sub1_targetProject.getText().toString();


                if (projectName.equals("")) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "请选择项目");
                } else if (projectName.indexOf('|') < 0) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "项目无项目编号!请选择项目");

                } else if (outTime.equals("")) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "请选择领料时间");

                } else if (lingLiaoRen.equals("")) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "请填写领料人");

                } else if (lingLiaoRenDianHua.equals("")) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "请填写领料人电话");

                } else if (receiveAdd.equals("")) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "请填写到货地点");

                } else if (getApplication() == null) {
                    ArmsUtils.makeText(StoreSubmitProject1Activity.this, "系统登录已过期，请重新登录");

                } else {

                    String[] proid = projectName.split("\\|");
//                    int user_id = ((dyjApplication) getApplication()).get_user_id();//物料员ID
                    int user_id = Integer.parseInt(sPreferencces.getString(BaseConstants.UID, ""));//物料员ID

                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                    String timestr = df.format(new Date());
                    String batchId = proid[1] + "TIME" + timestr;//出库单号

                    OutStorageList ol = new OutStorageList();
                    ol.setShenQingRen(s_sub1_userName.getText().toString());
                    ol.set_check_status("未审核");
                    ol.set_deal_status("未处理");
                    ol.set_check_user_id(check_id);
                    ol.set_check_user_name(check_user_name);
                    ol.set_target_project(targetProjectName);
                    ol.set_out_storage_estimate(outTime);
                    ol.set_receive_address(receiveAdd);
                    ol.set_receive_username(lingLiaoRen);
                    ol.set_receive_userphone(lingLiaoRenDianHua);
                    ol.set_material_user_id(user_id);
                    ol.set_out_storagelist_batchid(batchId);
                    ol.set_proid(proid[1]);
                    ol.set_projectName(proid[0]);
                    ol.set_submituid(user_id);
//                    ol.set_projectName(sPreferencces.getString(BaseConstants.COMPANY, ""));


                    Intent in = new Intent();
                    Bundle bunl = new Bundle();
                    bunl.putSerializable("outStorageList", ol);
                    bunl.putString("ling_liao_lei_xing", mLingLiaoLeiXing);
                    if (mLingLiaoLeiXing.equals("2")) { //如果是1为普通领料，2位电表领料
                        if (mMeterSearchConditionList.size() > 0) {
                            String jsonData = "[";
                            for (int i = 0; i < mMeterSearchConditionList.size(); i++) {
                                String data = mMeterSearchConditionList.get(i);
                                if (data.contains(":")) {
                                    jsonData += "{\"Key\":\"" + valuenamesHashMap.get(data.split(":")[0]) + "\",\"Value\":\"" + data.split(":")[1] + "\"},";
                                }

                            }
                            jsonData = ArmsUtils.cutLastString(jsonData);
                            jsonData += "]";
                            LogUtils.debugEInfo("jsonData===" + jsonData);
                            bunl.putString("searchcondition", jsonData);

                        }
                    } else {
                        bunl.putString("searchcondition", "");

                    }
                    in.putExtras(bunl);
                    in.setClass(StoreSubmitProject1Activity.this, StoreSubmitProject2Activity.class);
                    startActivityForResult(in, RESULT_CLOSE);

                }

            }
        });

        mUserId = sPreferencces.getString(BaseConstants.UID, "");

//        initSpinner1();
//        initSpinner2();
        initRecyclerView();

        getModelListProjectInfo();
        getChecUser();
        getOutStorageReceiver();


        btnRight.setText("下一步");

        //==============================
        mLingLiaoLeiXing = getIntent().getExtras().getString("ling_liao_lei_xing");
        if (mLingLiaoLeiXing.equals("2")) { //如果是1为普通领料，2位电表领料
            mLlDianBiaoChaXunTiaoJian.setVisibility(View.VISIBLE);
            GetMeterSearchCondition();
        } else {
            mLlDianBiaoChaXunTiaoJian.setVisibility(View.GONE);
        }

    }

    private void initRecyclerView() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 0, getResources().getColor(R.color.public_client_line_color)));
        mMeterSearchConditionAdapter = new MeterSearchConditionAdapter(getContext(), mMeterSearchConditionList, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mMeterSearchConditionAdapter);
    }

    private void getModelListProjectInfo() {


        String methodName = "GetModelListProjectInfo";

        SoapParams params = new SoapParams();
        params.put("user_id", mUserId);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                CProgressDialogUtils.cancelProgressDialog();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    li_projectInfo = projectInfo.getListFromJSON(result);
                    bindProjectInfo();

                } else {
                    return;
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                CProgressDialogUtils.cancelProgressDialog();

                ArmsUtils.makeText(StoreSubmitProject1Activity.this, error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                CProgressDialogUtils.cancelProgressDialog();


            }
        }, getAapiUserName(), getApiPwd());

    }

    private void getChecUser() {


        String methodName = "GetChecUser";

        SoapParams params = new SoapParams();
        params.put("user_id", mUserId);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                CProgressDialogUtils.cancelProgressDialog();


                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    li_checkUser = checkUser.getListFromJSON(result);
                    if (li_checkUser.size() > 0)
                        bindCheckUser(li_checkUser);
                } else {
                    return;
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                CProgressDialogUtils.cancelProgressDialog();

                ArmsUtils.makeText(StoreSubmitProject1Activity.this, error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                CProgressDialogUtils.cancelProgressDialog();


            }
        }, getAapiUserName(), getApiPwd());

    }

    /**
     * 选择领料人
     *
     * @return
     */
    private void getOutStorageReceiver() {


        String methodName = "GetOutStorageReceiver";

        SoapParams params = new SoapParams();

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                CProgressDialogUtils.cancelProgressDialog();


                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    mGetOutStorageReceivers = mGetOutStorageReceiver.getListFromJSON(result);
                    if (mGetOutStorageReceivers.size() > 0)
                        bindLingLiaoRenData(mGetOutStorageReceivers);
                } else {
                    return;
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                CProgressDialogUtils.cancelProgressDialog();

                ArmsUtils.makeText(StoreSubmitProject1Activity.this, error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                CProgressDialogUtils.cancelProgressDialog();


            }
        }, getAapiUserName(), getApiPwd());

    }

    private void GetMeterSearchCondition() {

        CProgressDialogUtils.showProgressDialog(this);
        String methodName = "GetMeterSearchCondition";
        SoapParams params = new SoapParams();

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                CProgressDialogUtils.cancelProgressDialog();


                String result = object.getProperty(methodName + "Result").toString();
                try {
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        List<GetMeterSearchCondition> getMeterSearchConditionList = new Gson().fromJson(result, new TypeToken<List<GetMeterSearchCondition>>() {
                        }.getType());


                        mSpinnerList1.add("请选择");

                        for (int i = 0; i < getMeterSearchConditionList.size(); i++) {
                            mSpinnerList1.add(getMeterSearchConditionList.get(i).getDisplayname());
                            valuenamesHashMap.put(getMeterSearchConditionList.get(i).getDisplayname(), getMeterSearchConditionList.get(i).getValuename());
                            valuesHashMap.put(getMeterSearchConditionList.get(i).getDisplayname(), getMeterSearchConditionList.get(i).getValuelist());

                        }
                        //                    dataNames.add("接线方式@connmode");
                        //                    dataNames.add("电压@elecpress");
                        //                    dataNames.add("容量@volume");
                        //                    dataNames.add("显示方式@displaytype");
                        //                    dataNames.add("有功等级@workgrade");
                        //                    dataNames.add("无功等级@noworkgrade");
                        //                    dataNames.add("通讯方式@commtype");


                        spinnerAdapter2 = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, mSpinnerList2);
                        //下拉的样式res
                        spinnerAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //绑定 Adapter到控件
                        spinner_2.setAdapter(spinnerAdapter2);

                        spinner_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            //parent就是父控件spinner
                            //view就是spinner内填充的textview,id=@android:id/text2
                            //position是值所在数组的位置
                            //id是值所在行的位置，一般来说与positin一致
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view,
                                                       int pos, long id) {
                                if (pos != 0) {

                                    mSelectedValue = String.valueOf(spinnerAdapter2.getItem(pos));
                                    LogUtils.debugEInfo("mSelectedValue=" + mSelectedValue);

                                    if (!mSelectedValue.equals("请选择")) {
                                        if (mMeterSearchConditionList.contains(mSelectedDisplayname + ":" + mSelectedValue)) {
                                            mMeterSearchConditionList.remove(mSelectedDisplayname + ":" + mSelectedValue);
                                        }

                                        mMeterSearchConditionList.add(mSelectedDisplayname + ":" + mSelectedValue);
                                        mMeterSearchConditionAdapter.notifyDataSetChanged();

                                        Handler handler = new Handler();
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                //设置ScrollView滚动到顶部
                                                nsv.fullScroll(ScrollView.FOCUS_DOWN);

                                                //设置ScrollView滚动到顶部
                                                //scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                                            }
                                        });
                                    }
                                }

                                //设置spinner内的填充文字居中
                                //((TextView)view).setGravity(Gravity.CENTER);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                // Another interface callback
                            }
                        });


                        spinnerAdapter1 = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, mSpinnerList1);
                        //下拉的样式res
                        spinnerAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //绑定 Adapter到控件
                        spinner_1.setAdapter(spinnerAdapter1);

                        spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            //parent就是父控件spinner
                            //view就是spinner内填充的textview,id=@android:id/text2
                            //position是值所在数组的位置
                            //id是值所在行的位置，一般来说与positin一致
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view,
                                                       int pos, long id) {

                                if (pos != 0) {

                                    mSelectedDisplayname = spinnerAdapter1.getItem(pos);
                                    mSelectedValuename = valuenamesHashMap.get(spinnerAdapter1.getItem(pos));

                                    LogUtils.debugEInfo("mSelectedDisplayname=" + mSelectedDisplayname);
                                    LogUtils.debugEInfo("mSelectedValuename=" + mSelectedValuename);

                                    mSpinnerList2.clear();
                                    spinnerAdapter2.clear();
                                    mSpinnerList2.add("请选择");
                                    spinnerAdapter2.notifyDataSetChanged();

                                    mSpinnerList2.clear();
                                    spinnerAdapter2.clear();
                                    mSpinnerList2.add("请选择");
                                    mSpinnerList2.addAll(valuesHashMap.get(spinnerAdapter1.getItem(pos)));
                                    spinnerAdapter2.notifyDataSetChanged();
                                    //                                mSelectedValue = String.valueOf(spinnerAdapter2.getItem(0));
                                    //                                LogUtils.debugEInfo("mSelectedValue=" + mSelectedValue);
                                    //设置spinner内的填充文字居中
                                    //((TextView)view).setGravity(Gravity.CENTER);
                                }

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {
                                // Another interface callback
                            }
                        });


                        //                    mSelectedDisplayname = spinnerAdapter1.getItem(1);
                        //                    mSelectedValuename = valuenamesHashMap.get(spinnerAdapter1.getItem(1));
                        //
                        //                    LogUtils.debugEInfo("mSelectedDisplayname=" + mSelectedDisplayname);
                        //                    LogUtils.debugEInfo("mSelectedValuename=" + mSelectedValuename);

                        mSpinnerList2.add("请选择");
                        //                    mSpinnerList2.addAll(valuesHashMap.get(spinnerAdapter1.getItem(1)));
                        //                    mSelectedValue = String.valueOf(spinnerAdapter2.getItem(1));
                        //
                        //                    LogUtils.debugEInfo("mSelectedValue=" + mSelectedValue);


                    } else {
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                CProgressDialogUtils.cancelProgressDialog();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                CProgressDialogUtils.cancelProgressDialog();


            }
        }, getAapiUserName(), getApiPwd());

    }

    // 绑定项目信息
    private void bindProjectInfo() {
        s_sub1_userName.setText(new StringBuilder().append(sPreferencces.getString(BaseConstants.USERNAME, "")).append("-").append(sPreferencces.getString(BaseConstants.MOBILE_PHONE, "")).toString());
        tv_shen_qing_dan_wei.setText(sPreferencces.getString(BaseConstants.COMPANY, ""));
        List<String> li_projects = new ArrayList<String>();
        if (li_projectInfo.size() > 0) {
            for (ProjectInfo p : li_projectInfo) {
                li_projects.add(p.get_projectname() + "|" + p.get_proid());
            }
        }


//        projectAda = new MyAutoAarryAdapter(StoreSubmitProject1Activity.this, R.layout.store_adapter_mylist_item, li_projects);
        projectAda = new MoHuArrayAdapter(this, R.layout.store_adapter_mylist_item, R.id.adapter_mylist, li_projects);//项目名称模糊查询
        s_sub1_project.setAdapter(projectAda);
        s_sub1_targetProject.setAdapter(projectAda);
    }

    private void bindCheckUser(List<CheckUser> li) {

        ArrayList<SpinnerItem> li_town_item = new ArrayList<SpinnerItem>();

        // SpinnerItem item0 = new SpinnerItem(0, "请选择审核人");
        // li_town_item.add(item0);

        for (CheckUser mh : li) {

            SpinnerItem item = new SpinnerItem(mh.get_check_id(), mh.get_user_name());

            li_town_item.add(item);
        }

        MyAutoAarryAdapter checkUserAda = new MyAutoAarryAdapter(
                StoreSubmitProject1Activity.this,
                R.layout.store_adapter_mylist_item, li_town_item);
        // ArrayAdapter<SpinnerItem> townAda = new ArrayAdapter<SpinnerItem>(
        // StoreSubmitProject1Activity.this,
        // android.R.layout.simple_spinner_item, li_town_item);
        checkUserAda.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

//        s_sub1_checker.setAdapter(checkUserAda);


        niceSpinner = (NiceSpinner) findViewById(R.id.s_sub1_checker);
        niceSpinner.setTextColor(getResources().getColor(R.color.gray_text));
//        ArrayList<String> dataset = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four", "Five"));
        ArrayList<String> dataset = new ArrayList();
        ArrayList<Integer> checkIds = new ArrayList();
        for (int i = 0; i < li_town_item.size(); i++) {
            dataset.add(li_town_item.get(i).GetValue());
            checkIds.add(li_town_item.get(i).GetID());
        }
        niceSpinner.attachDataSource(dataset);
        check_user_name = dataset.get(0);
        check_id = checkIds.get(0);
        niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                check_user_name = dataset.get(position);
                check_id = checkIds.get(position);
            }
        });


    }

    // 绑定审核人信息
    private void bindLingLiaoRenData(List<GetOutStorageReceiver> getOutStorageReceivers) {
        if (getOutStorageReceivers != null && getOutStorageReceivers.size() > 0) {

            niceSpinnerLingLiaoRen.setTextColor(getResources().getColor(R.color.gray_text));

            ArrayList<String> dataNames = new ArrayList();
            ArrayList<String> dataMobiles = new ArrayList();
            for (int i = 0; i < getOutStorageReceivers.size(); i++) {
                dataNames.add(getOutStorageReceivers.get(i).getName());
                dataMobiles.add(getOutStorageReceivers.get(i).getMobile());
            }
            niceSpinnerLingLiaoRen.attachDataSource(dataNames);
            receiveUser = dataNames.get(0);
            s_sub1_receiverPhone.setText(dataMobiles.get(0));
            niceSpinnerLingLiaoRen.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    s_sub1_receiverPhone.setText(dataMobiles.get(position));
                    receiveUser = dataNames.get(position);

                }
            });

        }
    }

    private void initSpinner1() {

        spinnerAdapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mSpinnerList1);
        //下拉的样式res
        spinnerAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        spinner_1.setAdapter(spinnerAdapter1);
        //选择监听
//        spinner_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            //parent就是父控件spinner
//            //view就是spinner内填充的textview,id=@android:id/text1
//            //position是值所在数组的位置
//            //id是值所在行的位置，一般来说与positin一致
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view,
//                                       int pos, long id) {
//                LogUtils.debugEInfo("选择了[" + mSpinnerList1.get(pos) + "]");
//                //设置spinner内的填充文字居中
//                //((TextView)view).setGravity(Gravity.CENTER);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                // Another interface callback
//            }
//        });
    }

    private void initSpinner2() {

        spinnerAdapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mSpinnerList2);
        //下拉的样式res
        spinnerAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        spinner_2.setAdapter(spinnerAdapter2);
        //选择监听
//        spinner_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            //parent就是父控件spinner
//            //view就是spinner内填充的textview,id=@android:id/text2
//            //position是值所在数组的位置
//            //id是值所在行的位置，一般来说与positin一致
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view,
//                                       int pos, long id) {
//                LogUtils.debugEInfo("选择了[" + mSpinnerList2.get(pos) + "]");
//                //设置spinner内的填充文字居中
//                //((TextView)view).setGravity(Gravity.CENTER);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//                // Another interface callback
//            }
//        });
    }

    // 日期控件
    protected Dialog onCreateDialog(int id) {
        // 用来获取日期和时间的
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = null;

        switch (id) {
            case 1:
                DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker datePicker, int year,
                                          int month, int dayOfMonth) {
                        // Calendar月份是从0开始,所以month要加1
//                        s_sub1_outTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth + " 09:00:00");
                        String currentDate = new StringBuilder().append(year).append("-").append(month + 1).append("-").append(dayOfMonth).toString();
//                        if (isDate2Bigger(currentDate, getNextTwoDay())) {
//                            ArmsUtils.makeText(StoreSubmitProject1Activity.this, "只能选择两天后的时间");
//                            return;
//                        } else {
                        s_sub1_outTime.setText(currentDate);
//                        }
                    }
                };
                dialog = new DatePickerDialog(this, dateListener,
                        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
//                dialog.getDatePicker().setMinDate(new Date().getTime());
                //设置可以选择的最小时间，业务需求是只能选择两天后的时间
                long time1 = Long.parseLong(date2TimeStamp(getNextTwoDayMill(), "yyyy-MM-dd HH:mm:ss"));
                dialog.getDatePicker().setMinDate(time1);
                break;
            case 2:
                DatePickerDialog.OnDateSetListener dateListener1 = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year,
                                          int month, int dayOfMonth) {
                        // Calendar月份是从0开始,所以month要加1
                        s_sub1_outTime.setText(new StringBuilder().append(year).append("-").append(month + 1).append("-").append(dayOfMonth).append(" 09:00:00").toString());
                    }
                };
                dialog = new DatePickerDialog(this, dateListener1,
                        calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                break;

            default:
                break;
        }

        return dialog;
    }

    /**
     * 时间转换为时间戳
     *
     * @param date
     * @param format
     * @return
     */
    public static String date2TimeStamp(String date, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
//            return String.valueOf(sdf.parse(date).getTime() / 1000);
            return String.valueOf(sdf.parse(date).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取两天后的日期时间戳
     *
     * @return
     */
    private String getNextTwoDayMill() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar claendar = Calendar.getInstance();
//        for (int i = 0; i < 2; i++) {
        claendar.add(Calendar.DATE, 2);//这个2可以随便改，几天后就改几就行
        System.out.println(sdf.format(claendar.getTime()));
//        }

        LogUtils.debugEInfo("getNextTwoDay=" + sdf.format(claendar.getTime()));
        return sdf.format(claendar.getTime());
    }

    /**
     * 获取两天后的日期
     *
     * @return
     */
    private String getNextTwoDay() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar claendar = Calendar.getInstance();
//        for (int i = 0; i < 2; i++) {
        claendar.add(Calendar.DATE, 2); //这个2可以随便改，几天后就改几就行
        System.out.println(sdf.format(claendar.getTime()));
//        }

        LogUtils.debugEInfo("getNextTwoDay=" + sdf.format(claendar.getTime()));
        return sdf.format(claendar.getTime());
    }

    @Override
    public void delMeterSearchCondition(String item) {
        mMeterSearchConditionList.remove(item);
        mMeterSearchConditionAdapter.notifyDataSetChanged();

        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                //设置ScrollView滚动到顶部
                nsv.fullScroll(ScrollView.FOCUS_DOWN);

                //设置ScrollView滚动到顶部
                //scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

    }

    /*
     * 成员内部类,此处为提高可重用性，也可以换成匿名内部类
     */
    private class BtnOnClickListener implements View.OnClickListener {

        private int dialogId = 0; // 默认为0则不显示对话框

        public BtnOnClickListener(int dialogId) {
            this.dialogId = dialogId;
        }

        @Override
        public void onClick(View view) {
            showDialog(dialogId);
        }

    }
}